import { useState, useEffect } from 'react';
import { usePersistFn } from 'ahooks';
import useWebSocket from '@/common/useWebsocket';

const useScoreState = () => {
  const [onlineCount] = useState(0);
  const [updateData, setUpdateData] = useState({ messageType: null, list: [] });

  // 错误消息
  const errorMessageHandle = usePersistFn((content) => {
    // eslint-disable-next-line
    console.error(content);
    // const err = content.message || content.textMessage;
    // if (!err) return;

    // return enqueueSnackbar(err);
  });

  // 赛事比分数据
  const scoreMessageHandle = usePersistFn(({ messageType, message }) => {
    setUpdateData({
      messageType,
      list: Array.isArray(message) ? message : [],
    });
  });

  // 消息回调
  const socketMessageHandle = usePersistFn((m) => {
    let res;
    try {
      res = JSON.parse(m);
    } catch {
      res = {};
    }
    const { errorCode, codeType: messageType, data: jsonString = '{}' } = res;
    let content;
    try {
      content = JSON.parse(jsonString);
    } catch {
      content = {};
    }

    if (errorCode !== 0) return errorMessageHandle(content);

    switch (messageType) {
      // 足球赛程信息推送
      case 100018: {
        const { textMessage } = content;
        const obj = {
          messageType,
          message: textMessage,
        };
        return scoreMessageHandle(obj);
      }
      // 篮球赛程信息推送
      case 100019: {
        const { textMessage } = content;
        const obj = {
          messageType,
          message: textMessage,
        };
        return scoreMessageHandle(obj);
      }
      default:
    }
  });

  // websocket连接
  const path = `youke_${new Date().getTime()}`;
  const { ws, connect, disconnect, send } = useWebSocket({
    path,
    msgType: 'jsonString',
    onMessage: socketMessageHandle,
    heartCheckMsg: { codeType: 100003, message: 'ping' },
  });
  useEffect(() => {
    connect();
    return disconnect;
  }, []);

  return {
    socket: ws,
    onlineCount,
    updateData,
    sendMessage: send,
  };
};

export default useScoreState;
